var express = require("express");
var router = express.Router();
const faceContrast = require("./face");
var fs = require("fs");

// 获取当前时间
function getTime() {
  let date = new Date(),
    year = date.getFullYear(),
    month =
      date.getMonth() + 1 < 10
        ? date.getMonth() + 1 + "0"
        : date.getMonth() + 1,
    day = date.getDate() < 10 ? date.getDate() + "0" : date.getDate(),
    HH = date.getHours() < 10 ? date.getHours() + "0" : date.getHours(),
    MM = date.getMinutes() < 10 ? date.getMinutes() + "0" : date.getMinutes(),
    SS = date.getSeconds() < 10 ? date.getSeconds() + "0" : date.getSeconds(),
    time = `${year}-${month}-${day} ${HH}时${MM}分${SS}秒`;
  return time;
}
// 看看文件夹
 function readfile(ip, data, data2) {
  var isexist = fs.existsSync("./public/img/" + ip);
  console.log("isexist", isexist);
  if (!isexist) {
    fs.mkdirSync("./public/img/" + ip);
  }
  var path = `./public/img/${ip}/${getTime()}camera.jpg`;
  var path2 = `./public/img/${ip}/${getTime()}upload.jpg`;
  writeImg(path, data);
  writeImg(path2, data2);
}

// 写文件
async function writeImg(path, data) {
  var dataBuffer = new Buffer(data, "base64");
  fs.writeFile(path, dataBuffer, function (err) {
    //用fs写入文件
    if (err) {
      console.log(err);
    } else {
      console.log(getTime() + "---写入成功！");
    }
  });
}

// 获取客户端IP
function getClientIp(req) {
  return (
    req.headers["x-forwarded-for"] || // 判断是否有反向代理 IP
    req.connection.remoteAddress || // 判断 connection 的远程 IP
    req.socket.remoteAddress || // 判断后端的 socket 的 IP
    req.connection.socket.remoteAddress
  );
}
// 人脸对比
router.post("/faceContrast", async (req, res, next) => {
  console.log("客户端ip", getClientIp(req));
  let IP = getClientIp(req);
  const { img1, img2 } = req.body;

  readfile(IP, img1, img2);
  let result = await faceContrast(img1, img2);
  console.log("对比结果", result);
  let data = {};
  if (result.ret === 20004) {
    data = {
      code: 400,
      message: "请检查选择和拍照的两张图像是否包含人脸",
    };
  } else if (result.ret === 0) {
    data = {
      code: 200,
      message: result.score > 0.67 ? "是同一个人" : "好像不是同一个人",
    };
  }
  res.jsonp(data);
});

module.exports = router;
